/*
 * File     : AbstractStructure.java
 * Created  : 10 Nov 2011
 *
 * Copyright © 2011 Matthew Wilson (mj. {my-surname} .uk {at} gmail.com)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.googlecode.dni.internal.structure;

import com.googlecode.dni.internal.DniInternal;
import com.googlecode.dni.type.NativeObject;
import com.googlecode.dni.type.Pointer;
import com.googlecode.dni.type.structure.Structure;

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;

/**
 * Base class for normal structures.
 *
 * @author Matthew Wilson
 */
public abstract class AbstractStructure implements Structure
{

    /**
     * The pointer.  This is public to help various things that want to directly
     * access the pointer without allocating a {@link Pointer} instance.
     */
    public final long pointer;

    /**
     * @param pointer
     *            the pointer
     */
    public AbstractStructure( final long pointer )
    {
        this.pointer = pointer;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public final Pointer pointer()
    {
        return Pointer.fromAddress( this.pointer );
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @SuppressFBWarnings( value = "BC_UNCONFIRMED_CAST",
                         justification = "getClass() will return a subclass of AbstractStructure" )
    public final boolean isSameObject( final NativeObject other )
    {
        return other.getClass() == getClass()
               && ( (AbstractStructure) other ).pointer == this.pointer;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public final void free()
    {
        DniInternal.ALLOCATOR.free( pointer() );
    }

    /**
     * @param structure
     *            the structure, or <code>null</code>
     * @return the address, or zero
     */
    public static long getAddress( final AbstractStructure structure )
    {
        return structure != null ? structure.pointer : 0;
    }

}
